<script setup lang='ts' name="add-menu">
import type { PlusColumn } from 'plus-pro-components'

import { departmentAddOrEdit, departmentList } from '@fl/api/iam-api'
import { SubmitBtn } from '@fl/components'
import { ElDialog } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref, toRefs, watch } from 'vue'

import { useTable } from '../hooks/use-table'
import { addOrganization, updateOrganization } from '@fl/api/joint-api'

const props = withDefaults(defineProps<{
    treeData?: any
    currentRow?: {
        id: string
        organizationName: string
        parentId: string
    }
    currentId?: string
    editSection?: boolean
    show: boolean
}>(), {
    treeData: () => { },
})

const emits = defineEmits(['confirm'])
const show = defineModel('show', {
    type: Boolean,
    default: false,
})
const editSection = defineModel('editSection', {
    type: Boolean,
    default: false,
})
const currentRow = defineModel('currentRow')
const { treeData, currentId } = toRefs(props)
console.log('🚀 ~ show add menu:', show, treeData, currentId.value)

// const { arrayToTree } = useTable()

const initialState = {
    companyId: '',
    companyName: '',
    organizationLevel: 1,
    organizationName: '',
    sortFlag: 1,
    parentId: currentId.value,
}
const form = ref(cloneDeep(initialState))
const formRef = ref()
const orgRef = ref()

// const equityOptions = ref<any>([])
// const equityOptionsOrigin = ref<any>([])

async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        console.log('form.value', form.value)
        if (editSection.value) {
            updateOrganization(form.value).then((res: any) => {
                console.log('🚀 ~ addOrganization ~ res:', res)
                if (res) {
                    close()
                    ElMessage.success('保存成功')
                    show.value = false
                    emits('confirm')
                }
            })
        }
        else {
            addOrganization(form.value).then((res: any) => {
                console.log('🚀 ~ addOrganization ~ res:', res)

                if (res) {
                    close()
                    ElMessage.success('保存成功')
                    show.value = false
                    emits('confirm')
                }
            })
        }
    }
}

function close() {
    formRef.value.formInstance.resetFields()
    show.value = false
}

// 选择上级部门
function parentIdChange(value) {
    const val = orgRef.value.getCheckedNodes()
    console.log('parentIdChange', value, val)
    const target = val[0].data
    form.value.parentId = value[0]
    form.value.companyId = target.id
    form.value.companyName = target.companyName
    form.value.organizationLevel = Number(target.organizationLevel) + 1
}

watch([() => currentRow.value, () => editSection.value], ([row, edit]) => {
    console.log('部门详情', row.organizationName, edit)
    if (edit) {
        form.value = {
            ...initialState,
            id: row.id,
            organizationName: row.organizationName,
            parentId: row.parentId,
        }
    }
    else {
        form.value = {
            ...initialState,
            parentId: row.id,
        }
    }
}, {
    deep: true,
})

const columns: PlusColumn[] = [
    {
        label: '上级部门',
        prop: 'parentId',
    },
    {
        label: '部门名称',
        prop: 'organizationName',
    },
    {
        fieldProps: { min: 1, precision: 0 },
        label: '排序',
        prop: 'sortFlag',
        valueType: 'input-number',
    },
]

const editColumns: PlusColumn[] = [
    {
        label: '部门名称',
        prop: 'organizationName',
    },
]

const rules = {
    organizationName: [
        {
            message: '请输入部门名称',
            required: true,
        },
    ],
    parentId: [
        {
            message: '请选择上级',
            required: true,
        },
    ],
}
</script>

<template>
    <ElDialog v-model="show"
              width="600"
              :title="currentId ? '编辑' : '新增'"
              @close="close"
    >
        <div class="mt-20">
            <PlusForm ref="formRef"
                      v-model="form"
                      :columns="editSection ? editColumns : columns"
                      :label-width="120"
                      :rules="rules"
                      :has-footer="false"
                      :row-props="{ gutter: 20 }"
            >
                <template #plus-field-parentId>
                    <el-cascader ref="orgRef"
                                 v-model="form.parentId"
                                 default-v
                                 :options="treeData"
                                 :props="{ label: 'organizationName', value: 'id', checkStrictly: true, multiple: false }"
                                 :show-all-levels="false"
                                 @change="parentIdChange($event)"
                    />
                </template>
            </plusform>
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="close">
                取消
            </el-button>

            <SubmitBtn type="primary"
                       @click="submit"
            >
                提交
            </SubmitBtn>
        </div>
    </ElDialog>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 50px;
}
</style>
